#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <string>
#include <memory>

// 事件基类
class Event {
public:
    virtual ~Event() = default;
    virtual std::string getType() const = 0;
};

// 事件处理器基类
class EventHandler {
public:
    virtual ~EventHandler() = default;
    virtual void handle(const std::shared_ptr<Event>& event) = 0;
};

// 事件分发器
class EventDispatcher {
private:
    std::map<std::string, std::vector<std::shared_ptr<EventHandler>>> handlers_;

public:
    // 注册事件处理器
    void registerHandler(const std::string& eventType, std::shared_ptr<EventHandler> handler) {
        handlers_[eventType].push_back(handler);
    }
    
    // 分发事件
    void dispatch(const std::shared_ptr<Event>& event) {
        auto it = handlers_.find(event->getType());
        if (it != handlers_.end()) {
            for (const auto& handler : it->second) {
                handler->handle(event);
            }
        }
    }
};

// 具体事件类型
class MouseClickEvent : public Event {
private:
    int x_, y_;
    
public:
    MouseClickEvent(int x, int y) : x_(x), y_(y) {}
    
    std::string getType() const override {
        return "MouseClickEvent";
    }
    
    int getX() const { return x_; }
    int getY() const { return y_; }
};

class KeyPressEvent : public Event {
private:
    char key_;
    
public:
    KeyPressEvent(char key) : key_(key) {}
    
    std::string getType() const override {
        return "KeyPressEvent";
    }
    
    char getKey() const { return key_; }
};

// 具体事件处理器
class MouseHandler : public EventHandler {
public:
    void handle(const std::shared_ptr<Event>& event) override {
        auto mouseEvent = std::dynamic_pointer_cast<MouseClickEvent>(event);
        if (mouseEvent) {
            std::cout << "Mouse clicked at (" << mouseEvent->getX() 
                      << ", " << mouseEvent->getY() << ")" << std::endl;
        }
    }
};

class KeyHandler : public EventHandler {
public:
    void handle(const std::shared_ptr<Event>& event) override {
        auto keyEvent = std::dynamic_pointer_cast<KeyPressEvent>(event);
        if (keyEvent) {
            std::cout << "Key pressed: " << keyEvent->getKey() << std::endl;
        }
    }
};

// 使用示例
int main() {
    EventDispatcher dispatcher;
    
    // 注册处理器
    dispatcher.registerHandler("MouseClickEvent", std::make_shared<MouseHandler>());
    dispatcher.registerHandler("KeyPressEvent", std::make_shared<KeyHandler>());
    
    // 产生事件
    dispatcher.dispatch(std::make_shared<MouseClickEvent>(100, 200));
    dispatcher.dispatch(std::make_shared<KeyPressEvent>('A'));
    dispatcher.dispatch(std::make_shared<MouseClickEvent>(300, 400));
    
    return 0;
}